package cn.tonyandmoney.voicenotes.ui.activity

import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import cn.tonyandmoney.anko.adapter.setKEmptyView
import cn.tonyandmoney.anko.extend.colorResId
import cn.tonyandmoney.voicenotes.R
import cn.tonyandmoney.voicenotes.greendao.utils.GreenDaoHelper
import cn.tonyandmoney.voicenotes.notes.entity.TNote
import cn.tonyandmoney.voicenotes.notes.presenter.INoteListPresenter
import cn.tonyandmoney.voicenotes.notes.presenter.INoteListView
import com.afollestad.materialdialogs.MaterialDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.zlzsy.app.base.ui.BaseActivity
import com.zlzsy.app.base.ui.adapter.KAdapter
import io.reactivex.Observable
import org.jetbrains.anko.*
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.swipeRefreshLayout

/**
 * 我的笔记界面
 * 设计到的功能
 * 1、我的笔记列表
 * 2、按关键词检索
 * 3、备忘录编辑
 * 4、备忘录分类
 */
class NotesListActivity : BaseActivity(), INoteListView,
        SwipeRefreshLayout.OnRefreshListener, AnkoLogger, BaseQuickAdapter.RequestLoadMoreListener {

    private val mPresenter: INoteListPresenter by lazy { INoteListPresenter.create(this, this) }
    private val mAdapter = KAdapter<TNote>()
    private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
    private val types = mutableListOf<String>()
    private val checkIds = mutableListOf<Int>()
    private var mKey: String? = null
    private var materialDialog: MaterialDialog? = null

    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        verticalLayout {
            swipeRefreshLayout {
                mSwipeRefreshLayout = this
                recyclerView {
                    layoutManager = LinearLayoutManager(ctx)
                    mAdapter.bindToRecyclerView(this)
                }
                setOnRefreshListener(this@NotesListActivity)
            }.lparams(matchParent, matchParent)
        }
        mAdapter.setItemView {
            frameLayout {
                topPadding = dip(10)
                relativeLayout {
                    padding = dip(10)
                    setBackgroundResource(android.R.color.white)
                    textView {
                        id = R.id.record_name
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        id = R.id.record_date
                    }.lparams(wrapContent, wrapContent) {
                        bottomOf(R.id.record_name)
                    }
                    textView {
                        id = R.id.record_type
                        textSize = 13f
                        singleLine = true
                        lines = 1
                    }.lparams(wrapContent, wrapContent) {
                        alignParentEnd()
                        rightOf(R.id.record_name)
                        leftMargin = dip(10)
                    }
                    textView {
                        id = R.id.record_memo
                        textSize = 13f
                        text = "无"
                    }.lparams(matchParent, wrapContent) {
                        bottomOf(R.id.record_date)
                    }

                }.lparams(matchParent, wrapContent)
                lparams(matchParent, wrapContent)
            }
        }.setDataBind { holder, note ->
            holder.setText(R.id.record_name, note.name)
            holder.setText(R.id.record_date, note.addTime)
            holder.setText(R.id.record_type, note.type)
            holder.setText(R.id.record_memo, note.memo)
        }.setKEmptyView(this) {
            frameLayout {
                lparams(matchParent, matchParent)
                textView {
                    textSize = 18f
                    colorResId = android.R.color.black
                    text = context.getString(R.string.empty_data)
                }.lparams(wrapContent, wrapContent) {
                    gravity = Gravity.CENTER
                }
            }
        }
    }


    override fun initData(savedInstanceState: Bundle?) {
        mAdapter.setOnLoadMoreListener(this, null)
        showLoadingDialog()
        mAdapter.setOnItemClickListener { _, _, position ->
            val entity = mAdapter.getItem(position) ?: return@setOnItemClickListener
            startActivity<NoteDetailsActivity>("noteId" to entity.id)
        }

        mAdapter.setOnItemLongClickListener { _, _, position ->
            val entity = mAdapter.getItem(position) ?: return@setOnItemLongClickListener false
            MaterialDialog.Builder(this)
                    .title("提示")
                    .content("是否要删除该笔记及其相关数据？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive { _, _ ->
                        mPresenter.delete(entity)
                        queryData(true)
                    }
                    .show()
            return@setOnItemLongClickListener true
        }
        queryData(true)
    }


    override fun showSearch(keywords: String) {
        materialDialog = MaterialDialog.Builder(this)
                .title("搜索")
                .input("请输入关键词", keywords, true, { _, input ->
                    mKey = input.toString()
                    queryData(true)
                })
                .positiveText("确定")
                .negativeText("取消")
                .show()
    }

    override fun cancel() {
        materialDialog?.dismiss()
        materialDialog = null
    }

    override fun confirm() {
        if (materialDialog == null) return
        val keywords = materialDialog?.inputEditText?.text?.toString()
        cancel()
        mKey = keywords ?: ""
        queryData(true)
    }

    /**
     * 刷新和按类型查找是相冲的
     * 分类了不在按关键字
     */
    private fun queryData(refresh: Boolean) {
        if (refresh) {
            types.clear()
            checkIds.clear()
            types.addAll(mPresenter.loadTypes())
        }

        val offset = if (refresh) 0 else mAdapter.data.size
        mPresenter.queryData(refresh, offset, mKey)
    }

    private fun queryByType(refresh: Boolean) {
        val checkTypes = mutableListOf<String>()
        Observable.range(0, checkIds.size)
                .subscribe {
                    val checkId = checkIds[it]
                    checkTypes.add(types[checkId])
                }
        if (checkTypes.size == types.size)
            checkTypes.clear()
        val offset = if (refresh) 0 else mAdapter.data.size
        mPresenter.searchByType(refresh, offset, checkTypes)
    }


    override fun setData(list: List<TNote>, canLoadMore: Boolean) {
        mAdapter.loadMoreComplete()
        if (!canLoadMore) mAdapter.loadMoreEnd()
        mAdapter.setEnableLoadMore(canLoadMore)
        mAdapter.setNewData(list)
        hideLoadingDialog()
        info("setData -> ${list.size}  $canLoadMore")
        mSwipeRefreshLayout.isRefreshing = false
    }

    override fun addData(list: List<TNote>, canLoadMore: Boolean) {
        mAdapter.loadMoreComplete()
        if (!canLoadMore) mAdapter.loadMoreEnd()
        mAdapter.setEnableLoadMore(canLoadMore)
        mAdapter.addData(list)
        hideLoadingDialog()
        info("addData -> ${list.size} $canLoadMore")
        mSwipeRefreshLayout.isRefreshing = false
    }

    override fun onResume() {
        super.onResume()
        GreenDaoHelper.session().tNoteDao.detachAll()
        GreenDaoHelper.session().clear()
        queryData(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.search_by_key) {
            MaterialDialog.Builder(this)
                    .title(getString(R.string.action_search))
                    .input("请输入关键词", mKey ?: "", true, { _, input ->
                        mKey = input.toString()
                        queryData(true)
                    })
                    .positiveText("确定")
                    .negativeText("取消")
                    .show()
            return true
        } else if (item.itemId == R.id.search_by_type) {
            MaterialDialog.Builder(this)
                    .title("按类型查找")
                    .items(types)
                    .itemsCallbackMultiChoice(checkIds.toTypedArray(), MaterialDialog.ListCallbackMultiChoice { _, which, _ ->
                        mKey = null
                        checkIds.clear()
                        checkIds.addAll(which.toList())
                        queryByType(true)
                        return@ListCallbackMultiChoice true
                    })
                    .positiveText("确定")
                    .negativeText("取消")
                    .show()

            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.note_list_menu, menu)
        return true
    }

    override fun onLoadMoreRequested() {
        if (TextUtils.isEmpty(mKey) && checkIds.isNotEmpty()) {
            queryByType(false)
        } else {
            queryData(false)
        }
    }

    /**
     * 刷新的时候，清空搜索关键词和选择类型
     */
    override fun onRefresh() {
        mKey = null
        checkIds.clear()
        queryData(true)
    }

}